/**
 * @author byte_su@163.com
 * @desc 暂时引用react-router-transition,更灵活\强大动画可以用react-motion
 * @date 2017-01-21
 */
import {RouteTransition} from "react-router-transition";
// import React from 'react';
// import React1 from 'react/lib/ReactWithAddons';

// var ReactCSSTransitionGroup = React1.addons.CSSTransitionGroup;

import {connect} from "react-redux";
import NavBottom from "../components/NavBottom";
import Header from "../components/Header";
import {Config, Fetch} from '../libs/';
import {Url} from '../libs/Url';
import {PAGE_SUBJECT} from '../stores/subject';
import {update_current_nav_item, clientInfoSet} from '../stores/action';
import slider from '../libs/slider';
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {height: window.innerHeight, current: 0};
        this._handleResize = this._handleResize.bind(this);
        this.next_time_out = this.next_time_out.bind(this);
    }

    componentDidMount() {
        const self = this;
        window.addEventListener('resize', this._handleResize);
        // this.next_time_out(); //调试注释
        // console.log(document.getElementById('main-container'));
        slider.init({
            elementId: 'main-container',//
            action: function (direction) {
                // console.log(direction);
                self.next_time_out(direction == 'right' ? -1 : undefined)
            }
        });
        document.body.addEventListener('touchmove', (ev) => {
            ev.preventDefault();
        });
    }

    next_time_out(current) {
        const self = this, {dispatch} = this.props;
        const state_ = this.props[PAGE_SUBJECT._GLOBAL];
        let keys = Object.keys(Config.ABSOLUTE_MENU);

        let next = current < 0 ? (self.props[PAGE_SUBJECT._GLOBAL].current - 1) :
            ((current != undefined ? current : self.props[PAGE_SUBJECT._GLOBAL].current) + 1);
        if (current < 0) {
            // next = ||
        }

        next = (next > (keys.length - 1) ? 0 : next);

        next = next < 0 ? (keys.length - 1) : next;
        dispatch(update_current_nav_item(PAGE_SUBJECT._GLOBAL, next));
        self.props.router.push({
            pathname: Config.ABSOLUTE_MENU[keys[self.props[PAGE_SUBJECT._GLOBAL].current]],
        });
    }

    parseSearch() {
        var resultObj = {};
        var search = window.location.search;
        if (search && search.length > 1) {
            var search = search.substring(1);
            var items = search.split('&');
            for (var index = 0; index < items.length; index++) {
                if (!items[index]) {
                    continue;
                }
                var kv = items[index].split('=');
                resultObj[kv[0]] = typeof kv[1] === "undefined" ? "" : kv[1];
            }
        }
        return resultObj;
    }

    componentWillMount() {
        const {dispatch} = this.props;
        // dispatch(fetchUser()) //获取登录用户信息
        //url search : {clientid:'',type:'window',brower:'',version:''}
        let clientInfo = this.parseSearch();
        if (this.props.clientInfo && !_.isEmpty(this.props.clientInfo)) {

        } else {
            if (clientInfo && clientInfo.clientid) {
                Fetch(Url.GET_CLASS, {body: {deviceid: clientInfo.clientid}})
                    .then((res)=> {
                        if (res['class'] && res['class'].classid) {
                            clientInfo['class'] = res['class'];
                            clientInfo['school'] = res['school'];
                            clientInfo['device'] = res['device'];
                            clientInfo['classroom'] = res['classroom'];
                            dispatch(clientInfoSet(clientInfo));
                            // dispatch(fetch({url: Url.HOME, classid: clientInfo.classid}));
                        } else {
                            alert('设备码没有跟班级对应，请核验!')
                        }
                    })
                    .catch(e=> {
                        console.log(e)
                    })
            } else {
                alert('设备码不合法，请核验!')
            }
        }

    }

    componentWillUnmount() {
        window.removeEventListener('resize', this._handleResize);
    }

    componentWillReceiveProps() {
    }

    _handleResize() {
        this.setState(Object.assign({}, this.state, {height: window.innerHeight}));
    }

    render() {
        const {dispatch} = this.props, self = this;
        return (
            <div style={{background: 'url(' + require('./../imgs/bg.jpg') + ')'}}>
                <div id="main-container"
                     className={'main-container'}>
                    <div
                        className="main"
                        style={{
                            height: this.state.height
                        }}>
                        <Header
                            {...this.props.clientInfo}
                        />
                        <RouteTransition
                            pathname={this.props.location.pathname}
                            atEnter={{translateX: 100}}
                            atLeave={{
                                translateX: -100
                            }}
                            atActive={{translateX: 0}}
                            mapStyles={styles => ({
                                transform: `translateX(${styles.translateX}%)`
                            })}
                            className="transition-wrapper"
                        >
                        {/*<ReactCSSTransitionGroup*/}
                            {/*transitionEnterTimeout={4}*/}
                            {/*transitionLeaveTimeout={4}*/}
                            {/*transitionName="amdox-router-transition">*/}
                            <div key="amdox-animation"

                                 style={{
                                     height: window.innerHeight - 180 - 120,
                                     padding: 40
                                 }}>
                                {this.props.children}
                            </div>
                        {/*</ReactCSSTransitionGroup>*/}
                        </RouteTransition>
                        <NavBottom
                            onClick={(current)=> {
                                clearInterval(self.timer);
                                self.next_time_out(current);
                            }}/>
                    </div>
                </div>
            </div>
        )
    }
}

// Which props do we want to inject, given the global state?
// Note: use https://github.com/faassen/reselect for better performance.
function select(state) {
    return {
        [PAGE_SUBJECT._GLOBAL]: state.pageBySubject[PAGE_SUBJECT._GLOBAL],
        clientInfo: state.clientInfo
    }
}

// 包装 component ，注入 dispatch 和 state 到其默认的 connect(select)(App) 中；
export default connect(select)(App)